package com.example.shixun2;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context; // 【新增】导入
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager; // 【新增】导入
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.MenuBuilder;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.view.WindowCompat;
import androidx.recyclerview.widget.GridLayoutManager; // 【新增】导入
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


public class MainActivity extends AppCompatActivity implements EmojiAdapter.OnEmojiClickListener {

    // 声明所有UI控件
    private Toolbar toolbar;
    private RecyclerView recyclerViewChat;
    private LinearLayout quickPhrasesContainer;
    private CheckBox cbTogglePhrases;
    private HorizontalScrollView hsvChipContainer;
    private ChipGroup chipGroup;
    private ImageView btnEmoji;
    private EditText etMessage;
    private ImageView btnAddOther;
    private Button btnSend;

    // 背景布局
    private ConstraintLayout mainContentLayout;
    private Random random = new Random();
    private int[] backgroundDrawables;

    // 声明 Adapter 和数据
    private ContactAdapter contactAdapter;
    private List<Contact> contactList;

    // ▼▼▼ 【新增】表情包面板相关 ▼▼▼
    private RecyclerView recyclerViewEmoji;
    private EmojiAdapter emojiAdapter;
    private List<String> emojiDataList;
    // ▲▲▲ 【新增】▲▲▲

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setStatusBarColor(Color.WHITE);
        WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView()).setAppearanceLightStatusBars(true);

        setContentView(R.layout.activity_main);

        // 1. 初始化 Toolbar
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // 2. 初始化所有UI控件
        initViews();

        // 3. 创建模拟数据 (用于联系人列表)
        initMockData();

        // 4. 设置 RecyclerView (聊天列表)
        setupRecyclerView();

        // 5. 设置所有点击事件
        initClickListeners();

        // 6. 设置表情包面板
        setupEmojiPanel();

        //
        backgroundDrawables = new int[]{
                R.drawable.background1,
                R.drawable.background2,
                R.drawable.background3,
                R.drawable.background4,
                R.drawable.background5
        };
    }

    /**
     * 找到 activity_main.xml 中的所有控件
     */
    private void initViews() {
        recyclerViewChat = findViewById(R.id.recycler_view_chat);
        quickPhrasesContainer = findViewById(R.id.quick_phrases_container);
        cbTogglePhrases = findViewById(R.id.cb_toggle_phrases);
        hsvChipContainer = findViewById(R.id.hsv_chip_container);
        chipGroup = findViewById(R.id.chip_group_phrases);
        btnEmoji = findViewById(R.id.btn_emoji);
        etMessage = findViewById(R.id.et_message);
        btnAddOther = findViewById(R.id.btn_add_other);
        btnSend = findViewById(R.id.btn_send);
        mainContentLayout = findViewById(R.id.main_content_layout);
        recyclerViewEmoji = findViewById(R.id.recycler_view_emoji);

    }

    /**
     * 创建联系人列表的模拟数据
     */
    private void initMockData() {
        contactList = new ArrayList<>();
        List<Message> messages1 = new ArrayList<>();
        messages1.add(new Message("你好，我是家人。", false));
        messages1.add(new Message("你好！", true));
        List<Message> messages2 = new ArrayList<>();
        messages2.add(new Message("加油！我们今晚去聚餐。", false));
        List<Message> messages3 = new ArrayList<>();
        messages3.add(new Message("今天也要努力工作！", true));
        messages3.add(new Message("不能再摸鱼了...", true));
        contactList.add(new Contact("家人", R.drawable.background1, messages1));
        contactList.add(new Contact("朋友", R.drawable.background2, messages2));
        contactList.add(new Contact("奋斗中的自己", R.drawable.background3, messages3));
    }

    /**
     * 设置 RecyclerView (联系人列表)
     */
    private void setupRecyclerView() {
        recyclerViewChat.setLayoutManager(new LinearLayoutManager(this));
        contactAdapter = new ContactAdapter(contactList, this);
        recyclerViewChat.setAdapter(contactAdapter);
    }

    /**
     * 设置表情包面板
     */
    private void setupEmojiPanel() {
        // 1. 创建表情数据源
        emojiDataList = new ArrayList<>();
        String[] emojis = {
                "😀", "😁", "😂", "🤣", "😃", "😄", "😅", "😆", "😉", "😊", "😋", "😎",
                "😍", "😘", "🥰", "😗", "😙", "😚", "🙂", "🤗", "🤩", "🤔", "🤨", "😐",
                "😑", "😶", "🙄", "😏", "😣", "😥", "😮", "🤐", "😯", "😪", "😫", "😴",
                "🤤", "😒", "😓", "😕", "🙃", "🤑", "😲", "☹️", "🙁", "😖", "😞", "😟",
                "😤", "😢", "😭", "😦", "😧", "😨", "😩", "🤯", "😬", "😰", "😱", "🥵",
                "🥶", "😳", "🤪", "😵", "😡", "😠", "🤬", "😷", "🤒", "🤕", "🤢", "🤮",
                "🤧", "😇", "🥳", "🥺", "🤡", "🤥", "🤫", "🤭", "😈", "👿", "💀", "👻",
                "👽", "🤖", "🎃", "👍", "👎", "👌", "✌️", "🤞", "🤟", "🤘", "👋", "🙏",
                "❤️", "💔", "💖", "💕", "👀", "🔥", "🎉", "✨"
        };
        for (String s : emojis) {
            emojiDataList.add(s);
        }

        // 2. 设置 Adapter (this 作为监听器)
        emojiAdapter = new EmojiAdapter(emojiDataList, this);
        recyclerViewEmoji.setAdapter(emojiAdapter);

        // 3. 设置 GridLayoutManager (每行8个表情)
        int spanCount = 8;
        recyclerViewEmoji.setLayoutManager(new GridLayoutManager(this, spanCount));
    }


    /**
     * 绑定所有的点击和交互事件
     */
    private void initClickListeners() {

        // 1. 快捷短语 CheckBox (保持不变)
        cbTogglePhrases.setOnCheckedChangeListener((buttonView, isChecked) -> {
            hsvChipContainer.setVisibility(isChecked ? View.VISIBLE : View.GONE);
        });

        // 2. 快捷短语 Chip 的点击事件 (保持不变)
        View.OnClickListener chipClickListener = v -> {
            Chip chip = (Chip) v;
            int cursorPosition = etMessage.getSelectionStart();
            String currentText = etMessage.getText().toString();
            String textToInsert = chip.getText().toString() + " ";
            String newText = currentText.substring(0, cursorPosition) +
                    textToInsert +
                    currentText.substring(cursorPosition);
            etMessage.setText(newText);
            etMessage.setSelection(cursorPosition + textToInsert.length());
        };
        findViewById(R.id.chip_phrase_1).setOnClickListener(chipClickListener);
        findViewById(R.id.chip_phrase_2).setOnClickListener(chipClickListener);
        findViewById(R.id.chip_phrase_3).setOnClickListener(chipClickListener);
        findViewById(R.id.chip_phrase_4).setOnClickListener(chipClickListener);


        // 3.表情包按钮 (btnEmoji)
        btnEmoji.setOnClickListener(v -> {
            // 检查表情面板当前是否可见
            if (recyclerViewEmoji.getVisibility() == View.VISIBLE) {
                // 如果可见：隐藏面板，显示键盘
                recyclerViewEmoji.setVisibility(View.GONE);
                showKeyboard();
            } else {
                // 如果不可见：先隐藏键盘，再显示面板
                hideKeyboard();
                // 稍微延迟显示，确保键盘完全收起
                v.postDelayed(() -> {
                    recyclerViewEmoji.setVisibility(View.VISIBLE);
                }, 100); // 100毫秒延迟

            }
        });

        etMessage.setOnClickListener(v -> {
            if (recyclerViewEmoji.getVisibility() == View.VISIBLE) {
                recyclerViewEmoji.setVisibility(View.GONE);

            }
        });


        // 5. “加号”按钮 (拓展功能)
        btnAddOther.setOnClickListener(v -> {
            Toast.makeText(MainActivity.this, "功能未开发", Toast.LENGTH_SHORT).show();
        });

        // 6. “发送”按钮 (核心逻辑)
        btnSend.setOnClickListener(v -> {
            String messageText = etMessage.getText().toString();
            if (messageText.isEmpty()) {
                Toast.makeText(MainActivity.this, "消息不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            Contact targetContact = null;
            for (Contact contact : contactList) {
                if (contact.isExpanded()) {
                    targetContact = contact;
                    break;
                }
            }
            if (targetContact == null) {
                Toast.makeText(MainActivity.this, "请先展开一个联系人来选择发送对象", Toast.LENGTH_LONG).show();
                return;
            }
            Message newMessage = new Message(messageText, true);
            targetContact.getMessageHistory().add(newMessage);
            etMessage.setText("");
            int targetPosition = contactList.indexOf(targetContact);
            if (targetPosition != -1) {
                contactAdapter.notifyItemChanged(targetPosition);
            }
            Toast.makeText(MainActivity.this, "消息已发送给 " + targetContact.getName(), Toast.LENGTH_SHORT).show();
        });
    }


    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 显示软键盘
     */
    private void showKeyboard() {
        etMessage.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(etMessage, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * 加载菜单
     */
    @SuppressLint("RestrictedApi")
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // ... 你的原有代码 ...
        getMenuInflater().inflate(R.menu.menu_main, menu);
        if (menu instanceof MenuBuilder) {
            ((MenuBuilder) menu).setOptionalIconsVisible(true);
        }
        return true;
    }

    /**
     * 处理菜单点击
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        // ... 你的原有代码 ...
        int id = item.getItemId();
        if (id == R.id.action_help_feedback) {
            HelpFeedbackFragment dialog = new HelpFeedbackFragment();
            dialog.show(getSupportFragmentManager(), "HelpFeedbackDialog");
            return true;
        } else if (id == R.id.action_change_background) {
            int randomIndex = random.nextInt(backgroundDrawables.length);
            mainContentLayout.setBackgroundResource(backgroundDrawables[randomIndex]);
            Toast.makeText(this, "背景已更换", Toast.LENGTH_SHORT).show();
            return true;
        } else if (id == R.id.action_share) {
            Toast.makeText(this, "点击了“分享”", Toast.LENGTH_SHORT).show();
            return true;
        } else if (id == R.id.action_about) {
            new AlertDialog.Builder(this)
                    .setTitle("关于")
                    .setMessage("本应用由小赖同学开发。")
                    .setPositiveButton("确定", null)
                    .show();
            return true;
        } else if (id == R.id.action_exit) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 处理表情包点击事件（实现自 EmojiAdapter.OnEmojiClickListener）
     * @param emoji 被点击的表情
     */
    @Override
    public void onEmojiClick(String emoji) {
        // 逻辑和“快捷短语”类似，但插入的是表情
        int cursorPosition = etMessage.getSelectionStart();
        String currentText = etMessage.getText().toString();

        // 将表情插入到光标位置
        String newText = currentText.substring(0, cursorPosition) +
                emoji +
                currentText.substring(cursorPosition);

        etMessage.setText(newText);
        etMessage.setSelection(cursorPosition + emoji.length()); // 移动光标到插入后
    }

}